﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using DAL;
using UtilityExtensions;
using BOL.Ventas;
using BOL.UI;
using BOL.RendicionVentas;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using UtilityExtensions;

namespace UILGestion.VentaAdmin.RendicionVenta
{
    public partial class RendicionVentaItemGrid : System.Web.UI.UserControl
    {

        private string RENDICIONVENTAINFO= "RendicionVentaItemInfo";
        private string LIQUIDACIONVENTA = "LiquidacionVentaInfo";
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void CancelItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = -1;
                itemGridView.FooterRow.Visible = true;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        //public void ValidaFooter(DataSet ds)
        //{
        //    var drw = (from a in ds.Tables[LIQUIDACIONVENTA].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
        //               select a).Sum(p => p.Field<decimal>("total"));
        //    var item = (from a in ds.Tables[RENDICIONVENTAINFO].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
        //                select a).Sum(p => p.Field<decimal>("total"));

        //    itemGridView.ShowFooter = true;

        //    if (item <= drw)
        //    {
        //        itemGridView.ShowFooter = false;
        //    }
        //}

        protected void buscarDocumento(object sender, EventArgs e)
        {
            try
            {


                //TextBox id =
                //    ((TextBox)itemGridView.FooterRow.FindControl("idDocimentoVenta"));


                //DAL.DocumentoVenta documentoVentaItem = DbUtil.Db.DocumentoVentas.Single(p => p.idInternal == id.Text.ToInt());

                //OrdenVentaItemInfo item = new Rendicion();


                //DataSet ds = (DataSet)Session[idColeccion.Value];

                //ds.Tables[ORDENVENTAITEMINFO].ImportRow(Util.EntidadToDataRow(item));

                //BindDataItem();
                //((OrdenVentaEditForm)this.Page).SetEstadistica();

                //GridUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void AddItem(OrdenVentaFormato documentoVenta)
        {
            try
            {
                RendicionVentaItemInfo item = new RendicionVentaItemInfo(documentoVenta, internalID.Value.ToInt());
                
                DataSet ds = (DataSet)Session[idColeccion.Value];

                // el documento no debe repetirse
                var w = from a in ds.Tables[RENDICIONVENTAINFO].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                        where a.Field<int>("idOrdenVentaFormato") == documentoVenta.idInternal
                        select a;
                if (w.Count() ==0)
                {
                    ds.Tables[RENDICIONVENTAINFO].ImportRow(Util.EntidadToDataRow(item));
                }
                
                BindDataItem();
                ((RendicionVentaEditForm)this.Page).SetEstadistica();

                itemUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                TextBox totalSaldo =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("totalTextBox"));

                TextBox totalOrigTextBox =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("totalOrigTextBox"));

                //no debe ser menor al ingresado origen
                if (totalSaldo.Text.ToDecimal().Value
                    > totalOrigTextBox.Text.ToDecimal().Value)
                {
                    throw new Exception("monto no puede ser mayor al permmitido {0:N}".Fmt(totalOrigTextBox.Text));
                }



                DataSet ds =
                (DataSet)Session[idColeccion.Value];

                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());

                var item = (from a in ds.Tables[RENDICIONVENTAINFO].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                            where a.Field<int>("idInternal") == idinternal
                            select a).First();

                 
                item["total"] = totalSaldo.Text.ToDecimal().Value;
                item["totalStr"] = String.Format("{0} {1:N}", item["simbol"], item["total"]); 

                gv.EditIndex = -1;

                BindDataItem();
                ((RendicionVentaEditForm)this.Page).SetEstadistica();

                itemGridView.FooterRow.Visible = false;

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = e.NewEditIndex;
                BindDataItem();
                itemGridView.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        


        public void Load(int idColeccion, int idParent)
        {
            this.idColeccion.Value = idColeccion.ToString();
            this.internalID.Value = idParent.ToString();
            BindDataItem();


        }
        public void LoadFromOrdenVentaFormato(int idColeccion, int idConcepto,int idParent, OrdenVentaFormato ordenVentaFormato)
        {
            this.idColeccion.Value = idColeccion.ToString();
            this.internalID.Value = idParent.ToString();
            this.idConcepto.Value = idConcepto.ToString();
            AddItem(ordenVentaFormato);
            // mostramos la edicion en caso de ser bono  o CH

            if (idConcepto == 2 | idConcepto == 3)
            {
                showEdit(true);
            }
            else
            {
                showEdit(false);
            }
            BindDataItem();
        }
        
        protected void DeleteItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                DataSet ds = (DataSet)Session[idColeccion.Value];

               
               
                var item = (from a in ds.Tables[RENDICIONVENTAINFO].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
                            where a.Field<int>("idInternal") == idInternal
                            select a).First();



                item.Delete();
                //eRolList.Tables[1].Rows.Remove(drw);

                Session[idColeccion.Value.ToString()] = ds;

                BindDataItem();
                ((RendicionVentaEditForm)this.Page).SetEstadistica();




            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<OrdenVentaItemInfo> itemList0 = new List<OrdenVentaItemInfo>();
                OrdenVentaItemInfo itemcero = new OrdenVentaItemInfo();

                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }

        public void BindDataItem()
        {

            DataSet ds = (DataSet)Session[idColeccion.Value];

            itemGridView.DataSource = ds.Tables[RENDICIONVENTAINFO];
            itemGridView.DataBind();
            resetEmpty();

        }

        public object DataSource
        {
            set { itemGridView.DataSource = value; }
        }

        public void HideFooter()
        {
            itemGridView.ShowFooter = false;
            itemGridView.DataBind();
        }
        public void HideEdit()
        {
            //ultimas  columnas
            var councolumans = itemGridView.Columns.Count;
            itemGridView.Columns[councolumans - 1].Visible = false;
            itemGridView.Columns[councolumans - 2].Visible = false;
            itemGridView.DataBind();
        }

        public void showEdit(bool val)
        {
            //ultimas  columnas
            var councolumans = itemGridView.Columns.Count;
            itemGridView.Columns[councolumans - 1].Visible = val;
            itemGridView.Columns[councolumans - 2].Visible = val;
            itemGridView.Columns[councolumans - 3].Visible = val;
            itemGridView.DataBind();
        }
    }
}